package cn.changeforyou.web.cloud.gateway.listener;

import cn.changeforyou.web.cloud.gateway.cache.LocalCache;
import cn.changeforyou.web.cloud.rpc.service.auth.AuthRpc;
import cn.changeforyou.web.cloud.rpc.service.auth.dto.ServiceInfoDTO;
import cn.changeforyou.web.cloud.rpc.service.auth.dto.SourceInfoDTO;
import com.alibaba.dubbo.config.annotation.Reference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author zhyu
 * @date 2019-07-10 11:22:30
 */

/**
 * 启动监听器
 *
 * @author Storezhang
 */
@Component
@Slf4j
public class StartupListener implements ApplicationListener<ContextRefreshedEvent> {

    @Reference
    private AuthRpc authRpc;
    @Resource
    private LocalCache localCache;

    @Override
    @Async
    public void onApplicationEvent(ContextRefreshedEvent event) {
        try {
            List<ServiceInfoDTO> serviceInfos = authRpc.getServiceInfos();
            List<SourceInfoDTO> sourceInfos = authRpc.getSourceInfos();
            localCache.addOrUpdateSource(sourceInfos);
            localCache.addOrUpdateService(serviceInfos);
            log.info("容器初始化监听器执行完毕");
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error("error", e);
            }
        }
    }
}
